using System;
using System.Data.SqlClient;
namespace YourNamespace
{
public partial class StudentDetails : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void AddButton_Click(object sender, EventArgs e)
{
try
{
// Connection string to your database
string connectionString = @"Data
Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\StudentDB.mdf;Integrated
Security=True;Connect Timeout=30;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "INSERT INTO Students (RollNo, Name, Class, Phone, Email) VALUES
(@RollNo, @Name, @Class, @Phone, @Email)";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@RollNo", int.Parse(RollNoTextBox.Text));
command.Parameters.AddWithValue("@Name", NameTextBox.Text);
command.Parameters.AddWithValue("@Class", ClassTextBox.Text);
command.Parameters.AddWithValue("@Phone", PhoneTextBox.Text);
command.Parameters.AddWithValue("@Email", EmailTextBox.Text);
command.ExecuteNonQuery();
}
}
MessageLabel.Text = "Student added successfully!";
MessageLabel.ForeColor = System.Drawing.Color.Green;
}
catch (SqlException ex)
{
MessageLabel.Text = $"Database error: {ex.Message}";
MessageLabel.ForeColor = System.Drawing.Color.Red;
}
catch (Exception ex)
{
MessageLabel.Text = $"An error occurred: {ex.Message}";
MessageLabel.ForeColor = System.Drawing.Color.Red;
}
}
protected void ShowButton_Click(object sender, EventArgs e)
{
string connectionString = @"Data
Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\StudentDB.mdf;Integrated
Security=True;Connect Timeout=30;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT * FROM Students";
using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
StudentsGridView.DataSource = reader;
StudentsGridView.DataBind();
}
}
}
}
}
}